#include <pthread.h>
#include "dohttp.h"
#include "data.h"
#include "thread_pool.h"

int main()
{
	int sock, ret;//代表信箱
	struct sockaddr_in server_addr;

	pthread_t pID;
	int *pClientSock=NULL;
	//1.创建信箱
	sock = socket(AF_INET, SOCK_STREAM, 0);

	//2.清空标签，写上地址和端口号
	bzero(&server_addr, sizeof(server_addr));

	server_addr.sin_family = AF_INET;//选择协议族IPV4
	// inet_pton(AF_INET, IP, &server_addr.sin_addr.s_addr);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//监听本地所有IP地址
	server_addr.sin_port = htons(SERVER_PORT);//绑定端口号

	//实现标签贴到收信的信箱上
	bind(sock, (struct sockaddr*)&server_addr, sizeof(server_addr));
	listen(sock, 128);//可以同时向我们的服务器发起链接的数量
	printf("等待客户端的连接\n");

	thread_pool_t pool;
	pool=thread_pool_create(2);//创建线程数

	while(1)
	{
		struct sockaddr_in client;
		int client_sock, len;
		char client_ip[64];//客户ip地址
		char buf[256];//接收客户端发送的内容；

		socklen_t client_addr_len;
		client_addr_len=sizeof(client);
		client_sock = accept(sock, (struct sockaddr*)&client, &client_addr_len);

		//打印客户端IP地址和端口号
		printf("client ip:%s\tport:%d\n", 
			inet_ntop(AF_INET, &client.sin_addr.s_addr, client_ip, sizeof(client_ip)),
			ntohs(client.sin_port));//打印客户端IP地址和端口号

		//************处理http请求，读取客户端发送的数据************

		//启动线程处理http请求
		pClientSock = (int*)malloc(sizeof(int));
		*pClientSock=client_sock;
		// pthread_create(&pID, NULL, doHttpRequest, (void *)pClientSock);
		thread_pool_add_task(pool, doHttpRequest, (void *)pClientSock);
	}
	
	close(sock);
	thread_pool_destroy(pool);//销毁线程
	return 0;
}




